<template>
  <div class="user-avatar">
    <el-upload
      class="avatar-uploader flex justify-center"
      :http-request="fileUploade"
      :show-file-list="false"
      accept="image/*"
      :drag="true"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <div class="auxiliary flex justify-center align-center">
        <i class="el-icon-plus avatar-uploader-icon"></i>
      </div>
    </el-upload>
  </div>
</template>

<script>
import { uploadApi } from '@/api/common.api.js';
import { FactoryStore } from '@/hooks';
import { GET_USER, USER_ACTION } from '@/utils/Const';
import { ref, getCurrentInstance } from 'vue';
export default {
	setup () {
		let { getter, action } = FactoryStore({
			namespaced : 'user',
			gettersMethod : [GET_USER],
			actionsMethod : [USER_ACTION]
		});
		let userInfo = getter[GET_USER];
		let defaultAvatar = require('@/assets/images/default-avatar.jpeg');
		const imageUrl = ref(userInfo.value.avatar || defaultAvatar);
		const { proxy } = getCurrentInstance();
		let fileUploade = async (file) => {
			let formData = new FormData();
			formData.append('file', file.file);
			let res = await uploadApi(formData);
			imageUrl.value = res.urls[0];
			action[USER_ACTION]({ ...userInfo.value, avatar : imageUrl.value });
			proxy.$message.success({
				message : '上传成功',
				type : 'success'
			});
		};
		return {
			userInfo,
			imageUrl,
			fileUploade
		};
	}
};
</script>

<style lang="scss">
.user-avatar {
  .el-upload-dragger {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    border: 0px;
    background: #eeeeee;
  }
  .avatar-uploader {
    position: relative;
    &:hover {
      .auxiliary {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1000;
        background: rgba(0, 0, 0, 0.5);
        .el-icon-plus {
          color: #fff;
        }
      }
    }
  }
  .avatar {
    width: 120px;
    height: 120px;
  }
  .auxiliary {
    width: 120px;
    height: 120px;
  }
  .el-icon-plus:before {
    font-weight: bold;
  }
}
</style>
